package bank;

import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class Bank {

	private ArrayList<ITransactionable> accounts;
	
	public Bank() {
		this.accounts = new ArrayList<ITransactionable>();
	}
	
	// register 
	public void register(ITransactionable transactor) {
		accounts.add(transactor);
	}
	
	public void commissionTransaction(String senderName, String recipientName, double amount) {
		// get the sender account
		ITransactionable sender = accounts.stream().parallel().filter(acc -> acc.getOwner() == senderName).findFirst().get();
		// get the recipient account
		ITransactionable recipient = accounts.stream().parallel().filter(acc -> acc.getOwner() == recipientName).findFirst().get();
		// check for nullity, just in case
		if (sender == null || recipient == null) {
			System.out.println("transaction failed, either sender or recipient is invalid");
		}
		// create actual transaction
		Transaction transaction = new Transaction(sender, recipient, amount);
		// issue transaction for sender
		sender.transfer(transaction);
		// issue transaction for recipient
		recipient.transfer(transaction);
	}
	
	public void commissionRandomTransaction() {
		// find a random sender
		int sender = ThreadLocalRandom.current().nextInt(0, accounts.size());
		// find a random recipient, one that's not the sender
		int recipient = sender;
		do {
			recipient = ThreadLocalRandom.current().nextInt(0, accounts.size());
		} while (recipient == sender);
		// figure out a random transaction amount
		double amount = ThreadLocalRandom.current().nextDouble(0, this.accounts.get(sender).getBalance());
		// alert for the BRAND NEW TRANSACTION
		System.out.println(String.format("NEW TRANSACTION INCOMING! %s sends %s $%f", this.accounts.get(sender).getOwner(), this.accounts.get(recipient).getOwner(), amount));
		// commission the transaction
		commissionTransaction(this.accounts.get(sender).getOwner(), this.accounts.get(recipient).getOwner(), amount);
	}

}